/*
 * Copyright (c) 2010, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/graph/GraphicsContext.h"
#include "alkes/graph/UpdateContext.h"
#include "alkes/graph/Screen.h"
#include "alkes/graph/Layer.h"

namespace alkes {

Screen::Screen(IGraphics2DDevice* device)
: graphics_context_(device)
, update_context_(device->createDefaultRenderTarget())
{
}

Screen::~Screen()
{
    Layer* layer;
    while (0 != (layer = static_cast<Layer*>(layer_list_.shift())))
    {
        removeLayer(layer);
        delete layer;
    }
}

bool Screen::initialize()
{
    return onCreate();
}

void Screen::finalize()
{
    onDestroy();
}

GraphicsContext& Screen::getGraphicsContext()
{
    return graphics_context_;
}

UpdateContext& Screen::getUpdateContext()
{
    return update_context_;
}

IGraphics2DDevice* Screen::getGraphics2DDevice()
{
    return graphics_context_.getGraphics2DDevice();
}

IGraphics3DDevice* Screen::getGraphics3DDevice()
{
    return graphics_context_.getGraphics3DDevice();
}

void Screen::setClearColor(const Color& color)
{
    clear_color_ = color;
}

const Color& Screen::getClearColor() const
{
    return clear_color_;
}

Layer* Screen::registerLayer()
{
    Layer* layer = new Layer();

    if (registerLayer(layer))
    {
        addLayer(layer);
    }
    else
    {
        delete layer;
        layer = 0;
    }

    return layer;
}

bool Screen::registerLayer(Layer* layer)
{
    return layer_list_.push(layer);
}

bool Screen::addLayer(Layer* layer)
{
    return container_.push(layer);
}

void Screen::removeLayer(Layer* layer)
{
    container_.remove(layer);

    if (layer_list_.remove(layer))
    {
        delete layer;
    }
}

bool Screen::update()
{
    bool ret = onUpdate();

    if (!ret)
        return ret;

    bool updated = false;
    ElementContainer::Iterator iter = layer_list_.getFirst();
    while (iter)
    {
        updated = iter_cast<Layer*>(iter)->update(update_context_) || updated;
        iter = iter->getNext();
    }

    return updated;
}

void Screen::render(const Rect* dirty_rect)
{
    if (dirty_rect)
        update_context_.addDirtyRect(*dirty_rect);

    uint16_t dirty_count;
    const Rect* dirty_rects = update_context_.getMergedRects(dirty_count);
    if (!(dirty_rects && dirty_count))
    {
        return ;
    }

    graphics_context_.getGraphics2DDevice()->beginDraw2D(update_context_.getRenderTarget());

    uint16_t i;
    for (i = 0; i < dirty_count; ++i) {

        onEraseBackground(dirty_rects[i], clear_color_);

        ElementContainer::Iterator iter = layer_list_.getFirst();
        while (iter)
        {
            iter_cast<Layer*>(iter)->render(graphics_context_, dirty_rects[i]);
            iter = iter->getNext();
        }
    }

    graphics_context_.getGraphics2DDevice()->endDraw2D();

    graphics_context_.getGraphics2DDevice()->flip();

    update_context_.resetDirtyRect();
}

bool Screen::onCreate()
{
    return true;
}

void Screen::onDestroy()
{
}

bool Screen::onUpdate()
{
    return true;
}

void Screen::onEraseBackground(const Rect& dirty_rects, const Color& color)
{
    IGraphics2DDevice* device = graphics_context_.getGraphics2DDevice();

    device->setScissorRect(dirty_rects);
    device->fill(color);
}

}
